﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Vroom.DataAccessLayer.Model;
using System.Data.Objects;
using Vroom.Utils.Logging;
using Vroom.Common.IFaces.Utils.Logging;
using Vroom.Common.Enums;
using System.Xml.Linq;
using System.Xml;
using System.Security;

namespace Vroom.Utils
{
    public class AuditLogger : IAuditLogger
    {
        ConfigEntities configEntities;

        public Guid   LoaderGuid    { get; set; }
        public Guid   ExecutionGuid { get; set; }        
        public string LoaderName    { get; set; }
        public int    StartLogId    { get; set; }

        public AuditLogger(Guid loaderGuid, Guid executionGuid, string source, string dest, string type)
        {
            LoaderGuid = loaderGuid;
            ExecutionGuid = executionGuid;
            LoaderName = SetLoaderName(source, dest, type);
        }
        

        public void LogStart(DateTime start)
        {
            ObjectParameter outParam = new ObjectParameter("idAuditLog", typeof(int));

            using (configEntities = new ConfigEntities())
            {
                configEntities.AuditLogMessageStart(LoaderGuid.ToString(), LoaderName, ExecutionGuid.ToString(), start, outParam);
            }

            StartLogId = (int) outParam.Value;
        }

        
        public void LogEnd(ValidationStatus validationStatus, string validationMessage, DateTime start, DateTime end, string error, int insertCount, int? updateCount)
        {
            string audit = new AuditData().GetAuditData(LoaderGuid.ToString(), LoaderName, start, end, error, insertCount, updateCount);

            using (configEntities = new ConfigEntities())
            {
                var result = configEntities.AuditLogMessageEnd((int?)StartLogId, DateTime.UtcNow, validationStatus.ToString(), validationMessage, audit);
            }           
        }


        private string SetLoaderName(string source, string dest, string type)
        {
            return "[ TYPE:" + type.ToUpper() + " | SRC:" + source + " | DEST:" + dest + " ]";
        }
    }
}
